package com.youlai.system.mqtt;

import io.netty.channel.DefaultEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.client.IMqttClientMessageListener;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.ByteBuffer;

@Service
@Slf4j
public class MqttSubClient {

    private MqttClient mqttClient;




    @PostConstruct
    public void init() {
        if (mqttClient == null) {
            try {
                mqttClient = MqttClient.create()
                        .ip("bziyun.com")
                        .port(8077)
                        .username("mica")
                        .password("mica")
                        .clientId("ManageWaySubClient:" + Math.random())
                        .cleanSession(Boolean.FALSE)
                        .reconnect(Boolean.TRUE)
                        .connect();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    public void send(String toic,String data){
        mqttClient.publish(toic,data.getBytes());
    }

    @EventListener
    public void start(ApplicationReadyEvent event) {
        if (mqttClient != null) {
            try {
                mqttClient.subQos0("/up/#", new MqttMessageListener());
                mqttClient.subQos1("/up/#", new MqttMessageListener());
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    public class MqttMessageListener implements IMqttClientMessageListener {

        DefaultEventLoopGroup defaultEventLoopGroup = new DefaultEventLoopGroup(500, new DefaultThreadFactory("MqttMessageThread111"));


        private String doObtainId(String topic) {

            int idx = topic.lastIndexOf("/");
            String mac = topic.substring(idx + 1);
            return mac;

        }

        @Override
        public void onMessage(String topic, ByteBuffer byteBuffer) {

        }
    }

}
